package edu.vt.ece.rt.quorum.messsages.types;

import edu.vt.ece.rt.QR;
import edu.vt.ece.rt.dstm.QObject;
import edu.vt.ece.rt.quorum.messsages.MessageHandler;
import edu.vt.ece.rt.quorum.messsages.QMessage;
import edu.vt.ece.rt.quorum.util.ReplyObjectStore;
import edu.vt.ece.rt.util.Logger.Logger;

/*
 * Read Request Response returned from all nodes in read Quorum
 * @author Sudhanshu
 */

public class ReadResponse extends QMessage implements Runnable {
	String Id;			//Specify the Object Id to be received
	Long txnId; 		//Specify the transaction number, Can be Converted to Context Class, if some MetaData required
	QObject qObj;
	boolean rw;

	public ReadResponse(String id, Long tid, QObject ob, boolean b) {
		super(MessageType.ReadResponse);
		Id = id;
		txnId = tid;
		qObj = ob;
		rw = b;
	}

	
	@Override
	public void run() {
		if (qObj != null) {
			Logger.debug("Got response of object "+qObj.getId()+" for "+txnId+ " from "+ this.getSrcAddr());
		} else {
			Logger.debug("Got response of object "+ Id +" for "+ txnId+ " not found ");
		}
		
		//Submit the object in request queue
		ReplyObjectStore rr = null;
//		if(rw){
			rr = MessageHandler.robjectRequestQueue.get(txnId + "-" + Id);			
//		}else{
//			rr = MessageHandler.wobjectRequestQueue.get(txnId + "-" + Id);		
//		}
		
		if(rr == null){
			Logger.fetal("NO Object store to reply");
			return;
		}
		
		rr.processMessage(qObj);		
	}	
	
	
	/*
	 * Test Read Response
	 */
	public static void main(String[] args) {
		try {
			QR.init();
//			ClustersManager.getCluster(Names.base).send(new ReadRequest("0-0", null, true));
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}
}
